# -*- coding: utf-8 -*-
# @Time    : 2024/05/07 15:40
# @Author  : Mr.su
# @FileName: maxmara.py
# @FileDesc: 
from CollectSpiders.settings import LOG_FILE_PATH
from CollectSpiders.toots.methods import make_md5
import scrapy, json, datetime, urllib.parse, logging
from CollectSpiders.toots.connects import RedisClient


# noinspection PyAbstractClass,PyMethodMayBeStatic
class CrawlSpider(scrapy.Spider):
    name, domain = 'maxmara', 'world.maxmara.com'
    redisClient = RedisClient()
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    }
    custom_settings = {
        'CONCURRENT_REQUESTS': 2,
        'LOG_FILE': LOG_FILE_PATH, 'LOG_LEVEL': 'WARNING'
    }

    def __init__(self, data=None, *args, **kwargs):
        """
        传入自定义参数
        :param data: 数据列表
        :param args:
        :param kwargs:
        """
        super(CrawlSpider, self).__init__(*args, **kwargs)
        self.data = json.loads(urllib.parse.unquote(data)) if data else {
            "pid": "1600", "status": 1, "wait_time": 3600, "brand": "maxmara",
            "childs": {
                "1601": {
                    "sid": "1501", "label": "女", "upload": 1, "status": 1, "webtype": "taobao",
                    "url": "http://world.maxmara.com/new-arrivals"
                }
            }
        }

    def start_requests(self):
        column = list(self.data['childs'].values())[0]
        if column['status'] == 1:
            new_url = column['url'] + '?focus=true&save=false&sort=topRated&page={}&isRefineSearch=false&q=%3AtopRated&resetQuery=true&preload=true'
            yield scrapy.Request(
                new_url.format(1), headers=self.headers, callback=self.process_lis,
                meta={'url': new_url, 'pg': 1}
            )

    def process_lis(self, response):
        column = list(self.data['childs'].values())[0]
        has_more = True
        for data in response.xpath('//*[@class="column"]/a'):
            detail_url = 'http://world.maxmara.com' + ''.join(data.xpath('./@href').extract_first()).strip()
            result = self.redisClient.conn.sadd('products', make_md5(detail_url))
            if not result:
                has_more = False
                break
            product = {
                '_id': '',
                'pid': self.data['pid'],
                'sid': column['sid'],
                'status': '0',  # 0:未下载  1:已下载  6:下载失败
                'webtype': column['webtype'],
                'url': detail_url,
                'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'brand': self.data['brand'],
                'image': [],
                'domain': self.domain,
                'label': column['label'],
                'upload': column['upload'],
                'name': ''.join(data.xpath('.//*[@class="short-description"]/text()').extract_first()).strip()
            }
            yield scrapy.Request(
                detail_url, headers=self.headers, callback=self.process_detail,
                meta={'product': product}
            )
        cursor = ''.join(response.xpath('//*[@class="infinite-scroll"]//text()').extract()).strip()
        if has_more and cursor:
            pg = response.meta['pg'] + 1
            new_url = response.meta['url']
            yield scrapy.Request(
                new_url.format(pg), headers=self.headers, callback=self.process_lis,
                meta={'url': new_url, 'pg': pg}
            )

    def process_detail(self, response):
        product = response.meta['product']
        img_lis = response.xpath('//*[@class="media-container"]/img/@data-image-zoom-src').extract()
        product['_id'] = make_md5(img_lis[0])
        product['image'] = img_lis
        logging.warning('<{}>: 数据id: {}'.format(self.domain, product['_id']))
        yield product
